<template>
<div class="app-container calendar-list-container">


<el-row>
  <el-col :span="4" style='margin-top:15px;'>

    <el-select class="filter-item" v-model="listQuery.sessions" placeholder="请选择届别" @change="jieChange">
      <el-option v-for="item in  jieOptions" :key="item" :label="'第' + item +'届'" :value="item"> </el-option>
    </el-select>

      <el-tree
        class="filter-tree"
        :data="treeData"
        node-key="type"
        highlight-current
        :props="defaultProps"
        :filter-node-method="filterNode"
        :default-expanded-keys="['0']"
        ref="menuTree"
        @node-click="getNodeData">
      </el-tree>
  </el-col>
  <el-col :span="20" style='margin-top:15px;'>
     <el-card class="box-card">
       <div class="talent-list-wrap">
           <div class="filter-container">
                <el-input class="filter-item" style="width: 200px;" @keyup.enter.native="handleFilter" placeholder="请输入姓名点击搜索" v-model="listQuery.name"> </el-input>
                <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
                <el-button class="filter-item fr" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit">添加</el-button>
                <!-- <el-button type="primary" v-if="menuManager_btn_edit" icon="edit" @click="handlerEdit">批量导入</el-button>
                <el-button type="primary" v-if="menuManager_btn_del" icon="delete" @click="handleDelete">批量导出</el-button> -->
            </div>

           <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
              <el-table-column align="center" label="序号" type="index" width="65">
              </el-table-column>
              <el-table-column width="180" align="center" label="姓名"> <template slot-scope="scope">
                    <span>{{scope.row.user.name}}</span>
                  </template> 
              </el-table-column>
              <el-table-column width="110" align="center" label="性别"> <template slot-scope="scope">
                      <span v-if="scope.row.user.sex == 1">男</span>
                      <span v-if="scope.row.user.sex == 0">女</span>
                    </template> 
              </el-table-column>

             <el-table-column width="200" align="center" label="账号"> <template slot-scope="scope">
                      <span>{{scope.row.user.username}}</span>
                    </template> 
              </el-table-column>
              <el-table-column width="250" align="center" label="所在院校"> <template slot-scope="scope">
                  <span>{{scope.row.user.schoolName}}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column width="180" align="center" label="科室"> <template slot-scope="scope">
                    <span>{{scope.row.updTime}}</span>
                  </template> 
              </el-table-column> -->
              <el-table-column width="200" align="center" label="联系电话"> <template slot-scope="scope">
                      <span>{{scope.row.user.mobile_phone}}</span>
                    </template> 
              </el-table-column>
              <el-table-column width="110" align="center" label="角色">
                 <template slot-scope="scope">
                    <span v-if="scope.row.group">{{scope.row.group.name}}</span>
                    <span v-else>--</span>
                </template>
              </el-table-column>

              <!-- <el-table-column width="110" align="center" label="密码"> <template slot-scope="scope">
                      <span>{{scope.row.username}}</span>
                    </template> 
              </el-table-column> -->

              <el-table-column fixed="right" align="center" width="250" label="操作"> <template slot-scope="scope">
                  <el-button size="small" type="success" @click="handleUpdate(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                  <el-button size="small" type="warning" @click="handleResetPwd(scope.row)">重置密码</el-button>
                </template> 
              </el-table-column>
            </el-table>
            <div v-show="!listLoading" class="pagination-container">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
            </div>
       </div>
     </el-card>
  </el-col>
</el-row>

<!--添加/编辑用户 START-->
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="beforeCloseHandle">
    <div class="dialog-form-wrap">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" class="form-item-near">
              <el-select class="filter-item" style="width: 100%;" v-model="form.sex" placeholder="请选择">
                <el-option v-for="item in  sexOptions" :key="item.value" :label="item.text" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="角色" prop="groupName">
          <el-select class="filter-item" style="width: 100%;" v-model="form.groupName" placeholder="请选择角色" value-key="id" @change="groupChange">
            <el-option v-for="item in  groupOptions" :key="item.id" :label="item.name" :value="item"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择区县" prop="areaName" v-if="areaSelectVisible">
          <el-select class="filter-item" style="width: 100%;" v-model="userScopeForm.areaName" placeholder="请选择区县" value-key="id" @change="areaSelectChange">
            <el-option v-for="item in  areaOptions" :key="item.id" :label="item.name" :value="item"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="届别" v-if="jieSelectVisible">
          <el-select class="filter-item" style="width: 100%;" v-model="userScopeForm.sessions" placeholder="请选择届别" @change="jieSelectChange">
            <el-option v-for="item in jieOptions" :key="item.id" :label="item" :value="item"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所在院校" v-if="schoolSelectVisible">
          <el-select class="filter-item" style="width: 100%;" v-model="userScopeForm.schoolName" placeholder="请选择所在院校" value-key="schoolId" @change="schoolChange">
            <el-option v-for="item in schoolOptions" :key="item.schoolId" :label="item.schoolName" :value="item"> </el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="班级" v-if="classSelectVisible">
          <el-select class="filter-item" style="width: 100%;" v-model="userScopeForm.classId" placeholder="请选择班级">
            <el-option v-for="item in classOptions" :key="item.id" :label="item.label" :value="item.id"> </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="联系电话" prop="mobilePhone">
          <el-input v-model="form.mobilePhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="登陆账号" prop="username">
              <el-input v-model="form.username" placeholder="请输入登陆账号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="form-item-near" label="密码" placeholder="请输入密码" prop="password">
              <el-input type="password" v-model="form.password" disabled></el-input>
              <span class="password-default-tip">默认密码为：123456</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="描述">
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 5}" placeholder="请输入内容" v-model="form.description"> </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel('form')">取 消</el-button>
      <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
      <el-button v-else type="primary" @click="update('form')">确 定</el-button>
    </div>
  </el-dialog>
<!--添加/编辑用户 END-->
</div>
</template>

<script>
import {
   page, fetchTree, fetchTreeObj, getObj, addObj, delObj, putObj,getAreaListObj,
   fetchJieOptionsObj,fetchSchoolListObj,getUserScopeObj, getUserGroupObj,resetPwdObj
} from 'api/admin/person/index';
import { fetchClassTreeObj } from 'api/admin/talent/index';

import { mapGetters } from 'vuex';
import { debug } from 'util';
export default {
  name: 'menu',
  components: {
    'menu-element': () => import('./components/element')
  },
  data() {
    return {
      filterText: '',
      list: null,
      total: null,
      formEdit: true,
      formAdd: true,
      formStatus: '',
      showElement: false,
      classSelectVisible: false,
      jieSelectVisible: false,
      schoolSelectVisible: false,
      areaSelectVisible: false,
      typeOptions: ['menu', 'dirt'],
      listQuery: {
        name: null,
        schoolId:null,
        classId: null
      },
      groupOptions: [],//角色列表
      areaOptions: [],
      schoolOptions: [],
      treeData: [],
      jieOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      labelPosition: 'right',
      rules: {
        name: [
          {
            required: true,
            message: '请输入用户',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur'
          }
        ],
        groupName: [
          {
            required: true,
            message: '选择角色',
            trigger: 'change'
          }
        ],
        username: [
          {
            required: true,
            message: '请输入登陆账号',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ]
      },
      form: {
        id: null,
        name: null,
        sex: null,
        groupId: null,
        mobilePhone: null,
        username:null,
        password: 123456
      },
      userScopeForm: {
        areaId:null,
        sessions: null,
        schoolId:null,
        classId: null
      },
      currentId: -1,
      menuManager_btn_add: false,
      menuManager_btn_edit: false,
      menuManager_btn_del: false,
      sexOptions: [ { text:'男', value: '1' },{ text:'女',value: '0'}],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      tableKey: 0
    }
  },
  watch: {
    filterText(val) {
      this.$refs.menuTree.filter(val);
    }
  },
  created() {
    //初始化届下拉数据
    this.getJieOptions();
    this.getAllGroupTypeList();
    this.getList();
    this.getAreaOptionsData();
  },
  computed: {
    ...mapGetters([
      'elements'
    ])
  },
  methods: {
    getAllGroupTypeList() {
      //默认获取角色类型下的角色列表
      fetchTree({groupType: 1}).then(data => {
        data = this.filterGroupData(data);
        this.groupOptions = data;
      });
    },
    filterGroupData(data){
      var currentRole = this.$store.getters.roles[0];
      // var groups = ['GLY','QYGLY','XGLY','LRY'];
      var gly = 'GLY',
          qygly = 'QYGLY',
          xgly = 'XGLY';
      //首先排除掉管理员
      data = data.filter(item => {
        return item.code != gly;
      });
      if(currentRole.code == qygly){
          data = data.filter(item => {
            return item.code != qygly;
          });
      }else if(currentRole.code == xgly){
          data = data.filter(item => {
            return item.code != qygly && item.code != xgly;
          });
      }
      return data;
    },
    //获取届列表
    getJieOptions() {
      fetchJieOptionsObj().then(res => {
        if(res && res.data){
          this.jieOptions = res.data;
          this.listQuery.sessions = res.data[0];
          this.getClassTree(res.data[0]);
        }
      });
    },
    jieChange (jieId) {
     this.jieId = jieId;
     this.getClassTree(jieId);
    },
    //获取班级树
    getClassTree(jieId) {
      var param = {sessions: jieId};
      fetchClassTreeObj(param).then(res => {
        if(res && res.data){
          this.treeData = JSON.parse(res.data.areaSchoolTreeList);
        }
      });
    },
    getList() {
      this.listLoading = true;
      page(this.listQuery)
        .then(response => {
          this.list = response.data.rows;
          this.total = response.data.total;
          this.listLoading = false;
        })
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getAreaOptionsData() {
      //默认获取马鞍山的所有区
      var param = {pid: '368100142709874688'};
      getAreaListObj(param).then(response => {
        this.areaOptions = response.data;
      });
    },

    groupChange(group) {
      this.form.groupId = group.id;
      this.form.groupName = group.name;
      this.form.groupCode = group.code;
      //区域管理员
     if(group.code == 'QYGLY'){
       this.areaSelectVisible = true;
       //20200424
       this.jieSelectVisible = true;
     }
     //校管理员
     else if(group.code == 'XGLY'){
       this.areaSelectVisible = true;
       this.jieSelectVisible = true;
       this.schoolSelectVisible = true;
     }
     //录入员
     else if(group.code == 'LRY'){
       this.areaSelectVisible = true;
       this.jieSelectVisible = true;
       this.schoolSelectVisible = true;
       this.classSelectVisible = true;
     }else{
       this.areaSelectVisible = false;
       this.jieSelectVisible = false;
       this.schoolSelectVisible = false;
       this.classSelectVisible = false;
     }
    },
    areaSelectChange(area) {
      this.userScopeForm.areaId = area.id;
      this.userScopeForm.areaName = area.name;
    },
    jieSelectChange() {
      var param = {
        areaId: this.userScopeForm.areaId,
        sessions: this.userScopeForm.sessions
      }
      fetchSchoolListObj(param).then(res => {
        if(res && res.data){
          this.schoolOptions = res.data;
        }
      });
    },
    schoolChange(school) {
      this.userScopeForm.schoolId = school.schoolId;
      this.userScopeForm.schoolName = school.schoolName;
    },
    getNodeData(data) {
      if (data.type == 1) {
        this.listQuery.areaId = data.id;
        this.listQuery.schoolId = null;
        this.listQuery.classId = null;
      }else if(data.type == 2){
        this.listQuery.areaId = null;
        this.listQuery.schoolId = data.id;
        this.listQuery.classId = null;
      }else if(data.type == 3){
        this.listQuery.areaId = null;
        this.listQuery.schoolId = null;
        this.listQuery.classId = data.id;
      }else{
        this.listQuery.areaId = null;
        this.listQuery.schoolId = null;
        this.listQuery.classId = null;
      }
    },
    handlerEdit() {
      if (this.form.id) {
        this.formEdit = false;
        this.formStatus = 'update';
      }
    },
    handlerAdd() {
      this.resetForm();
      this.formEdit = false;
      this.formStatus = 'create';
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(row.user.id).then(() => {
          this.getList();
          this.resetForm();
          this.onCancel();
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          });
        });
      }).catch(() => {
          //点击取消         
      });
    },
    handleResetPwd(row) {
      this.$confirm('确认重置密码吗(重置后密码为123456)?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPwdObj({userId: row.user.id}).then((res) => {
          if(res.rel){
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 2000
            });
          }else{
            this.$message.error('操作失败!');
          }
        });
      }).catch(() => {
          //点击取消         
      });
    },
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false;
          //userObj赋值
          // var userObj = this.form;
          var bsList = this.getUserScopeList();
          var params = {
            user: JSON.stringify(this.form),
            bizUserScopeList: JSON.stringify(bsList),
            group: JSON.stringify({
              id: this.form.groupId,
              code: this.form.groupCode,
              name: this.form.groupName,
            })
          }
          putObj(params).then(() => {
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },
    getUserScopeList(){
      var userScopeList = [];
        userScopeList.push(
            {
              userId: this.form.id,
              userName: this.form.username,
              areaId: this.userScopeForm.areaId,
              areaName: this.userScopeForm.areaName,
              sessions: this.userScopeForm.sessions,
              schoolId: this.userScopeForm.schoolId,
              schoolName: this.userScopeForm.schoolName
            }
        );
      return userScopeList;
    },
    onCancel() {
      this.formEdit = true;
      this.formStatus = '';
    },
    resetForm() {
      this.form = {
        name: null,
        sex: null,
        groupId: null,
        mobilePhone: null,
        username:null,
        password: 123456
      };
      this.userScopeForm = {
        areaId:null,
        sessions: null,
        schoolId:null,
        classId: null
      },
      this.jieSelectVisible = false;
      this.areaSelectVisible = false;
      this.schoolSelectVisible = false;
      this.classSelectVisible = false;
    },

    handleFilter() {
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      getObj(row.user.id).then(response => {
          this.form = response.data;
          //设置group信息
          if(row.group){
            this.form.groupId = row.group.id;
            this.form.groupName = row.group.name;
            this.form.groupCode = row.group.code;
          }
          this.dialogFormVisible = true;
          this.dialogStatus = 'update';
      });
      getUserScopeObj({userId: row.user.id}).then(response => {
        if(response.data){
          this.userScopeForm = response.data;
          this.setFormItemVisible();
          //用户的管理范围值赋给form
          if(response.data.areaId){
            this.form.areaId = response.data.areaId;
            this.form.areaName = response.data.areaName;
          }
          if(response.data.schoolId){
            this.form.schoolId = response.data.schoolId;
          }
        }
      });
    },
    //设置各表单item是否展示
    setFormItemVisible(){
        if(this.userScopeForm.areaId){
          this.areaSelectVisible = true;
        }
        if(this.userScopeForm.sessions){
          this.jieSelectVisible = true;
        }
        if(this.userScopeForm.schoolId){
          this.schoolSelectVisible = true;
        }
        if(this.userScopeForm.classId){
          this.classSelectVisible = true;
        }
      },
    getUserGroup(userId) {
      getUserGroupObj(userId).then(response => {
        if(response.data){
          //用户的角色值赋给form
          if(response.data.areaId){
            this.form.areaId = response.data.areaId;
             this.areaSelectVisible = true;
          }
          if(response.data.schoolId){
            this.form.schoolId = response.data.schoolId;
             this.schoolSelectVisible = true;
          }
        }
      });
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delObj(row.id)
            .then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              });
              const index = this.list.indexOf(row);
              this.list.splice(index, 1);
            });
        }).catch(() => {
          //点击取消         
      });
    },
    create(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {

          var bsList = this.getUserScopeList();
          var params = {
            user: JSON.stringify(this.form),
            bizUserScopeList: JSON.stringify(bsList),
            group: JSON.stringify({
              id: this.form.groupId,
              code: this.form.groupCode,
              name: this.form.groupName,
            })
          }

          putObj(params)
            .then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              });
            })
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.dialogFormVisible = false;
      // this.$refs[formName].resetFields();
      this.resetForm();
    },
    beforeCloseHandle() {
      this.resetForm();
    }

  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.talent-list-wrap{
  .el-form-item{
    margin-bottom: 10px;
  }
}
.dialog-form-wrap{
  padding-right: 20px;
  .form-item-near{
    .el-form-item__label{
      width: 70px!important;
    }
    .el-form-item__content{
          margin-left: 70px!important;
    }
  }
}
.password-default-tip{
  font-size: 12px;
  color: #6d6d6d;
  margin-top: -8px;
  height: 16px;
}

</style>